package com.Lixiaoqian.PartyHistoryMuseum.ui;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

import com.Lixiaoqian.PartyHistoryMuseum.R;
import com.Lixiaoqian.PartyHistoryMuseum.adapter.BannerAdapter;
import com.Lixiaoqian.PartyHistoryMuseum.base.BaseActivity;
import com.Lixiaoqian.PartyHistoryMuseum.bean.BannerBean;
import com.Lixiaoqian.PartyHistoryMuseum.bean.BannerData;
import com.Lixiaoqian.PartyHistoryMuseum.net.ApiFactory;
import com.Lixiaoqian.PartyHistoryMuseum.net.BannerApi;
import com.Lixiaoqian.PartyHistoryMuseum.utils.AnimUtils;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Constant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.DensityUtil;
import com.Lixiaoqian.PartyHistoryMuseum.utils.PrefUtils;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Utils;
import com.Lixiaoqian.PartyHistoryMuseum.view.WaveView;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 *
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.recycleView)
    RecyclerViewPager recycleView;

    BannerAdapter bannerAdapter;
    @BindView(R.id.iv_line)
    ImageView ivLine;
    @BindView(R.id.waveView)
    WaveView waveView;
    @BindView(R.id.Xcircleindicator)
    com.Lixiaoqian.PartyHistoryMuseum.view.Xcircleindicator Xcircleindicator;

    private BannerData zipData = null;
    private Handler handler;
    private Runnable wheelRun;
    private int time = 5000;
    private int i = 0;
    private BannerData bannerData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getBannerApi();
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initObject() {
        super.initObject();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                i++;
                if (i >= bannerData.getData().size()) {
                    i = 0;
                    Xcircleindicator.setCurrentPage(0);
                }
                recycleView.smoothScrollToPosition(i);
                handler.postDelayed(wheelRun, time);
            }
        };
        /*权限*/
        permissionChecker.checkPsOpen(this, Constant.PERMISS_WRITE_STORE, Constant.PERMISS_READ_STORE);

        /**recyceView*/
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL);
        CustomSGLayoutManager skyLayoutManager = new CustomSGLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);//实例化自定义类
        skyLayoutManager.setSpeedRatio(1);//设置其速度因子
        recycleView.setLayoutManager(skyLayoutManager);
        recycleView.addItemDecoration(dividerItemDecoration);
        recycleView.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
            @Override
            public void OnPageChanged(int i, int i1) {
                MainActivity.this.i = i1;
                Xcircleindicator.setCurrentPage(i1);
            }

        });
        waveView.setDuration(5000);
        waveView.setStyle(Paint.Style.FILL);
        waveView.setColor(getResources().getColor(R.color.ligth_yellow));
        waveView.setInterpolator(new LinearInterpolator());
    }

    /**
     * 扫描线动画开始
     */
    private void startLineAnim() {
        AnimUtils.AnimBuild animBuild = new AnimUtils.AnimBuild().selectAnimName(0)
                .setDuration(4000)
                .setInterStyle(0)
                .setRESTART(true)
                .setValue(DensityUtil.px2dip(mActivity, 0), DensityUtil.dip2px(mActivity, 50));
        AnimUtils.startAnim(ivLine, animBuild);
    }

    /**
     * 扫描线动画暂停
     */
    private void pauseLineAnim() {
        AnimUtils.pauseAinm();
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        getWikitdeApi();
        startLineAnim();
        // diffuseView.start();
        waveView.start();
    }


    @OnClick({R.id.centerImage})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.centerImage:
               enterARorDown();
               // startActivity(new Intent(this,TestActivity.class));
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        waveView.stop();
        pauseLineAnim();
    }

    @Override
    protected void onStop() {
        super.onStop();
        waveView.stopImmediately();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (handler != null) {
            handler.removeCallbacks(wheelRun);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            permissionChecker.checkPsOpen(this, Constant.PERMISS_WIRITE_READ);
        }
    }

    public void getBannerApi() {
        BannerApi bannerApi = ApiFactory.getBannerApiSingleton();
        final Call<BannerData> banner = bannerApi.getBanner("20170918142913345082", "banner");
        banner.enqueue(new Callback<BannerData>() {
            @Override
            public void onResponse(Call<BannerData> call, Response<BannerData> response) {
                bannerData = response.body();
                Log.i("tag", "onResponse: " + bannerData.getData().get(0).getCover_image());
                if (bannerData != null) {
                    bannerAdapter = new BannerAdapter(MainActivity.this, bannerData.getData());
                    Xcircleindicator.setPageTotalCount(bannerData.getData().size());
                    recycleView.setAdapter(bannerAdapter);
                    startWheel();
                }
            }

            @Override
            public void onFailure(Call<BannerData> call, Throwable t) {
                Log.i("log", "onFailure: 失败");
            }
        });
    }

    public void getWikitdeApi() {
        BannerApi bannerApi = ApiFactory.getBannerApiSingleton();
        final Call<BannerData> banner = bannerApi.getBanner("20170918142913345082", "scanPackSource");
        banner.enqueue(new Callback<BannerData>() {
            @Override
            public void onResponse(Call<BannerData> call, Response<BannerData> response) {
                zipData = response.body();
            }

            @Override
            public void onFailure(Call<BannerData> call, Throwable t) {

            }
        });
    }

    private void enterARorDown() {
        String zipPath = Constant.ZIP_PATH;
        if (zipData != null) {
            Utils.createFolde(zipPath);
            BannerBean bannerBean = zipData.getData().get(0);
            String create_date = bannerBean.getCreate_date();
            String loc_data = PrefUtils.getString(Constant.PRE_ZIP_DATA, "", mActivity);
            if (!create_date.equals(loc_data)) {//更新资源包
                LoadActivity.launch(mActivity, bannerBean);
            } else {//直接进入AR世界
                ArCamActivity.launch(mActivity);
            }
        } else {
            if (Utils.isFolder(zipPath)) {
                ArCamActivity.launch(mActivity);
            }
        }
    }

    /**
     * 自动轮播
     */
    private void startWheel() {
        wheelRun = new Runnable() {
            @Override
            public void run() {
                if (mActivity != null && !MainActivity.this.isFinishing()) {
                    handler.sendEmptyMessage(0);
                }
            }
        };
        handler.postDelayed(wheelRun, time);
    }

    public class CustomSGLayoutManager extends StaggeredGridLayoutManager {
        private double speedRatio;

        public CustomSGLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        public CustomSGLayoutManager(int spanCount, int orientation) {
            super(spanCount, orientation);
        }

        @Override
        public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
            int a = super.scrollHorizontallyBy((int) (speedRatio * dx), recycler, state);//屏蔽之后无滑动效果，证明滑动的效果就是由这个函数实现
            if (a == (int) (speedRatio * dx)) {
                return dx;
            }
            return a;
        }

        public void setSpeedRatio(double speedRatio) {
            this.speedRatio = speedRatio;
        }
    }


}